package pl.pawluk.inz.dao.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.support.DataAccessUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;
import pl.pawluk.inz.dao.AuthoritiesMapper;
import pl.pawluk.inz.dao.IUsersService;
import pl.pawluk.inz.dao.UsersMapper;
import pl.pawluk.inz.dto.UserDTO;
import pl.pawluk.inz.entities.*;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author: toshiba
 * Date: 06.03.13
 * Time: 20:16
 * To change this template use File | Settings | File Templates.
 */
@Service
public class UsersService extends AbstractService<UserDTO, Users> implements IUsersService {

    UsersService() {
        super(UserDTO.class, Users.class);
    }

    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private AuthoritiesMapper authoritiesMapper;


    @Override
    public User findByName(String email) {
        UsersCriteria uc = new UsersCriteria();
        uc.createCriteria().andEmailEqualTo(email);
        List<Users> users = usersMapper.selectByExample(uc);
        if (users == null || users.size() != 1) {
            return null;
        }
        Users e = users.get(0);
        Set<GrantedAuthority> auths = new HashSet<GrantedAuthority>();
        AuthoritiesCriteria c = new AuthoritiesCriteria();
        c.createCriteria().andUserIdEqualTo(e.getId());
        List<AuthoritiesKey> authoritiesKeys = authoritiesMapper.selectByExample(c);
        if (authoritiesKeys != null) {
            for (final AuthoritiesKey k : authoritiesKeys) {
                auths.add(new GrantedAuthority() {
                    @Override
                    public String getAuthority() {
                        return k.getAuthority();
                    }
                });
            }
        }
        return new User(e.getEmail(), e.getPassword(), e.getActive(), e.getActive(), e.getActive(), e.getActive(), auths);
    }

    @Override
    public UserDTO getUserInfo(String email) {
        UsersCriteria c = new UsersCriteria();
        c.createCriteria().andEmailEqualTo(email);
        return convertToDTO(DataAccessUtils.uniqueResult(usersMapper.selectByExample(c)));
    }
}
